package com.ruoyi.controller;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.dto.MessageDTO;
import com.ruoyi.message.domain.IotBroadcastMessage;
import com.ruoyi.message.domain.IotMessage;
import com.ruoyi.message.service.IIotBroadcastMessageService;
import com.ruoyi.message.service.IIotMessageService;
import com.ruoyi.server.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.websocket.Session;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/message")
public class MessageController {

    /**
     * 单聊消息发送接口
     * @param messageDTO 包含发送者、接收者和消息内容
     * @return 操作结果
     */
    @Autowired
    private IIotMessageService iotMessageService;
    @Autowired
    IIotBroadcastMessageService iotBroadcastMessageService;
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @PostMapping("/sendPrivateMessage")
    public AjaxResult sendPrivateMessage(@RequestBody MessageDTO messageDTO) {
        try {
            messageDTO.setFromUserId(SecurityUtils.getUserId());

            // 检查必要参数是否为空
            if (messageDTO.getFromUserId() == null || messageDTO.getToUserId() == null || messageDTO.getContent() == null) {
                return AjaxResult.error("缺少必要参数：fromUserId、toUserId、content 均为必填");
            }
            //先存入数据库
            IotMessage iotMessage = new IotMessage();
            iotMessage.setMessageType(messageDTO.getType());
            iotMessage.setContent(messageDTO.getContent());
            iotMessage.setSendTime(messageDTO.getFormattedTime());
            iotMessage.setUserId(messageDTO.getToUserId());
            iotMessageService.insertIotMessage(iotMessage);
            // 获取目标用户会话
            Map<Long, Session> userSessions = WebSocketServer.getUserSessions();
            Session targetSession = userSessions.get(messageDTO.getToUserId());

            if (targetSession != null && targetSession.isOpen()) {
                System.out.println("发送给用户：" + messageDTO);
                // 发送消息给目标用户
                targetSession.getBasicRemote().sendText(messageDTO.toString());
                return AjaxResult.success("消息发送成功");
            } else {
                return AjaxResult.success("用户在线后会发起通知");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("消息发送失败：" + e.getMessage());
        }
    }

    /**
     * 群发消息发送接口
     * @param messageDTO 包含发送者和消息内容（toUserId为空表示群发）
     * @return 操作结果
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @PostMapping("/sendBroadcastMessage")
    public AjaxResult sendBroadcastMessage(@RequestBody MessageDTO messageDTO) {
        System.out.println(messageDTO.toString()+"群发消息");
        try {
            messageDTO.setFromUserId(SecurityUtils.getUserId());
            // 检查必要参数是否为空
            if (messageDTO.getFromUserId() == null || messageDTO.getContent() == null) {
                return AjaxResult.error("缺少必要参数：fromUserId、content 均为必填");
            }

            //先存入数据库
            IotBroadcastMessage iotBroadcastMessage = new IotBroadcastMessage();
            iotBroadcastMessage.setMessageType(messageDTO.getType());
            iotBroadcastMessage.setContent(messageDTO.getContent());
            iotBroadcastMessage.setSendTime(messageDTO.getFormattedTime());
            iotBroadcastMessage.setReadStatus("1");
            iotBroadcastMessageService.insertIotBroadcastMessage(iotBroadcastMessage);

            Map<Long, Session> userSessions = WebSocketServer.getUserSessions();
            int successCount = 0;
            int failCount = 0;

            for (Session session : userSessions.values()) {
                if (session.isOpen()) {
                    try {
                        session.getBasicRemote().sendText(messageDTO.toString());
                        successCount++;
                    } catch (Exception e) {
                        failCount++;
                    }
                }
            }

            return AjaxResult.success("群发消息完成", 
                "成功发送给 " + successCount + " 个用户，" + failCount + " 个用户发送失败");

        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("群发消息失败：" + e.getMessage());
        }
    }
    @GetMapping("/getOnlineUsers")
    public AjaxResult getOnlineUsers() {
        try {
            // 获取所有在线用户ID（从userSessions的key集合转换为列表）
            List<Long> onlineUserIds = new ArrayList<>(WebSocketServer.getUserSessions()
                    .keySet());
//            List<String> onlineUserIds = WebSocketServer.getUserSessions()
//                    .keySet()
//                    .stream()
//                    .collect(Collectors.toList());
            return AjaxResult.success("获取在线用户成功", onlineUserIds);

        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取在线用户失败：" + e.getMessage());
        }
    }
}